import { useRequest } from 'ahooks'
import { Form, Input, InputNumber, Modal } from 'antd'
import { memo, useEffect } from 'react'
import { chargeMoney, getCompanyBalance } from '../services'

export interface ChargeModalProps {
  userId?: string
  balance?: number
  onCancel?: (refresh: boolean) => void
}

const ChargeModal: React.FC<ChargeModalProps> = props => {
  const [chargeForm] = Form.useForm()
  const { runAsync, loading } = useRequest(chargeMoney, {manual: true})
  const { data: companyBalance, run: _getCompanyBalance, mutate } = useRequest(getCompanyBalance, {manual: true})

  const onCancel = (refresh: boolean) => {
    props.onCancel?.(refresh)
  }

  const onOk = () => {
    chargeForm.validateFields().then((values: any) => {
      runAsync(values).then(() => {
        onCancel(true)
      })
    })
  }

  useEffect(() => {
    if (props.userId) {
      chargeForm.setFieldsValue({
        userId: props.userId
      })
      _getCompanyBalance()
    } else {
      chargeForm.resetFields()
      mutate(undefined)
    }
  }, [props.userId])
  
  return (
    <Modal
      title='授信'
      open={!!props.userId}
      onCancel={() => onCancel(false)}
      onOk={onOk}
      confirmLoading={loading}
      destroyOnClose
    >
      <Form form={chargeForm} name='chargeForm'>
        <Form.Item name='userId' noStyle><Input hidden /></Form.Item>
        <Form.Item label='金额' required>
          <div style={{display: 'flex', gap: 8}}>
            <Form.Item name='amount' noStyle rules={[
              {required: true, message: '请输入充值金额'},
              {validator: (_, value) => {
                if (value !== 0) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('充值金额不可为 0'));
              }}
            ]}>
              <InputNumber placeholder='最大 10,000' style={{flex: 1}} addonAfter='元' precision={2} min={-(props.balance || 0)} max={Math.max((companyBalance?.data.balance || 0), 10000)} />
            </Form.Item>
            <div style={{width: 'max-content', flexShrink: 0, display: 'flex', alignItems: 'center', color: 'red', gap: 8}}>
              <span>用户授信余额{(props.balance || 0).toFixed(2)}元</span>
              <span>企业余额{(companyBalance?.data.balance || 0).toFixed(2)}元</span>
            </div>
          </div>
          <div>正数表增加，负数表回收</div>
        </Form.Item>
        <Form.Item name='commend' label='备注'>
          <Input.TextArea placeholder='请输入' style={{width: '100%', height: 80}} maxLength={150} showCount />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default memo(ChargeModal)
